package com.vue.cn.controller;

import com.vue.cn.common.http.AjaxResult;
import com.vue.cn.common.http.StatusEnum;
import com.vue.cn.domin.Employee;
import com.vue.cn.service.EmployeeService;
import com.vue.cn.utils.code.Code;
import com.vue.cn.utils.mail.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("employeeLogin")
public class EmployeeLoginController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MailUtils mailUtils;

    @GetMapping("sendCode")
    public AjaxResult getCode( String email){
        //通过邮箱查询数据库，判断是否有该员工
        Employee byEmail = employeeService.findByEmail(email);
        if (byEmail==null) {
            return AjaxResult.error(StatusEnum.EEEOR_NOT_REGITER);
        }
        //发送验证码给该用户,验证码存入redis缓存,设置5分钟后失效
        redisTemplate.opsForValue().set(email,Code.numCode(),5L,TimeUnit.MINUTES);
        mailUtils.sendCode(email,Code.numCode());

        return AjaxResult.ok();
    }

    @GetMapping("login")
    public AjaxResult login(HttpSession session,String email, String code){
        //通过邮箱查询数据库，判断是否有该员工
        Employee byEmail = employeeService.findByEmail(email);
        if (byEmail==null) {
            return AjaxResult.error(StatusEnum.EEEOR_NOT_REGITER);
        }
        //查看缓存中是否有数据，如果没有返回验证码错误
        String s = redisTemplate.opsForValue().get(email);
        if (StringUtils.isEmpty(s)||StringUtils.isEmpty(code)||!code.equals(s)) {
            return AjaxResult.error(StatusEnum.EEEOR_CODE);
        }
        //查看用户是否激活
        if (!byEmail.getActive()) {
            return AjaxResult.error(StatusEnum.EEEOR_ACTIVE);
        }
        redisTemplate.delete(email);
        //将用户信息放入session中，并清除该用户的验证码从缓存中清除
        session.setAttribute("user",byEmail);
        redisTemplate.delete(email);

        return AjaxResult.ok();
    }


}
